var page = require('webpage').create();
var fs = require("fs");
var sys = require("system");
//page.settings.loadPlugins=false;
page.settings.webSecurityEnabled = true;
page.settings.localToRemoteUrlAccessEnabled = false;
//page.settings.resourceTimeout=3600;

var userAgents=[
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2950.0 Iron Safari/537.36",
                ];

var random_int = parseInt(Math.random() * (userAgents.length - 1) + 1);
page.settings.userAgent =userAgents[random_int];
page.viewportSize = {width: 1440, height: 900};


page.onConsoleMessage = function (msg) {
    console.log(msg);
};
// page.onResourceRequested = function(requestData, request) {
//    console.log('loading', requestData['url']);
// };

page.onCallback = function(data) {
    path = "recodelist";
    fs.write(path, data, 'a');
    fs.write(path, '\n', 'a');
};


//var url = sys.args[1];
var url = "https://auth.alipay.com/login/index.htm";


console.log(url);
    page.open(url, function (status) {
});


function sleep(milliSeconds){
      var startTime = new Date().getTime(); // get the current time
      while (new Date().getTime() < startTime + milliSeconds); // hog cpu
}

function sendstring(string){
    for(var i in string){
         var string_a = string[i];
         page.sendEvent('keypress', string_a);
         sleep(parseInt(Math.random() * 500) + 300);
    }
}

var username = "85897930@qq.com";
var password = "ydf123456";

var had_user = false;

setTimeout(
    function () {
        had_user = page.evaluate(function () {
            var u_data = document.getElementById('J-input-user');
            if (u_data==null) {
                return false;
            }
            var value = u_data.value;
            if (value) {
                return true;
            }
            return false;
        });

        console.log(had_user);
        page.render('code0.png');

        sleep(100);
        if(!had_user){
            sendstring(username);
            page.sendEvent('keypress', page.event.key.Tab);
        }
        sendstring(password);
        sleep(200);
        page.sendEvent('keypress', page.event.key.Enter);

        console.log(page.url)
        page.render('code1.png');
    }, 8 * 1000);


// https://my.alipay.com/portal/i.htm


setTimeout(function () {
    page.render('recode.png');
    console.log(page.url)
}, 20 * 1000);



function loop(){
    page.open("https://my.alipay.com/portal/i.htm?referer=https%3A%2F%2Fauth.alipay.com%2Flogin%2Findex.htm");
    setTimeout(function () {
        page.open("https://lab.alipay.com/consume/record/items.htm", 
            function (status) {
                var recode = page.evaluate(function () {
                                        var recordlist = document.getElementsByClassName("record-list");
                                        length = recordlist.length;
                                        if(length==0){
                                            return false;
                                        }
                                        for (var i = recordlist.length - 1; i >= 0; i--) {
                                            var item = recordlist[i];
                                            var tmp_data = {}
                                            tmp_data['number'] = item.getElementsByClassName('number')[0].innerText;
                                            tmp_data['time'] = item.getElementsByClassName('time')[0].innerText;
                                            tmp_data['info'] = item.getElementsByClassName('info')[0].innerText;
                                            tmp_data['amount'] = item.getElementsByClassName('amount')[0].innerText;
                                            window.callPhantom(JSON.stringify(tmp_data));
                                        }
                                        return true;
                                    });


                if (recode!=true) {
                    page.render('over.png');
                    phantom.exit(200);
                }

            // body...
        })
        // body...
    }, 5*1000);

}

setTimeout(function () {
    var interval = setInterval(loop,  30*1000);
}, 40 * 1000);

